<template>
  <div>
    <el-button
      type="primary"
      style="float: left; margin-bottom: 10px"
      :size="size"
      @click="handleRefresh"
    >刷新</el-button>
    <el-button
      type="primary"
      v-if="isOperate"
      style="float: left; margin-bottom: 10px"
      :size="size"
      icon="el-icon-plus"
      @click="viewDetails"
    >新增</el-button>
    <el-table
      :data="tableData"
      :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }"
      style="width: 100%"
      v-loading="tableloading"
      :size="size"
    >
      <el-table-column type="index" width="45"> </el-table-column>
      <el-table-column width="40" v-if="isOperate">
        <template slot-scope="scope">
          <i class="el-icon-delete icon_style" title="删除" @click="handleDelete(scope.row)"></i>
        </template>
      </el-table-column>
      <el-table-column width="40" v-if="isOperate">
        <template slot-scope="scope">
          <i class="el-icon-sort icon_style" title="排序" @click="handleSort(scope.row)"></i>
        </template>
      </el-table-column>
      <el-table-column width="40">
        <template slot-scope="scope">
          <i
            :class="!isOperate ? 'el-icon-view icon_style' : 'el-icon-edit icon_style'"
            :title="!isOperate ? '查看' : '编辑'"
            @click="lookDetails(scope.row)"
          ></i>
        </template>
      </el-table-column>
      <el-table-column prop="visitName" label="访视名称" width="180"> </el-table-column>
      <el-table-column prop="visitNum" label="访视编号" width="180"> </el-table-column>
      <el-table-column prop="visitType" label="访视类型" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.visitType == '1'">公共</span>
          <span v-if="scope.row.visitType == '2'">非公共</span>
          <span v-if="scope.row.visitType == '3'">计划外</span>
          <span v-if="scope.row.visitType == '4'">循环</span>
        </template>
      </el-table-column>
      <el-table-column prop="edcVisitWindow.visitBaseline.visitName" label="基线访视" width="180"> </el-table-column>
      <el-table-column prop="edcVisitWindow.tableBaseline.visitTableName" label="基线表"> </el-table-column>
      <el-table-column prop="edcVisitWindow.fieldName" label="基线日期" :formatter="formatDate">
        <template slot-scope="scope"
        ><label>{{
          scope.row.edcVisitWindow != null &&
            scope.row.edcVisitWindow.tableBaseline != null &&
            scope.row.edcVisitWindow.tableBaseline.fieldList != null
            ? scope.row.edcVisitWindow.tableBaseline.fieldList[0].fieldName
            : ''
        }}</label></template
        ></el-table-column
      >
      <el-table-column prop="edcVisitWindow.intervalNum" label="间隔"> </el-table-column>
      <el-table-column prop="edcVisitWindow.intervalType" label="间隔单位">
        <template slot-scope="scope">
          <span v-if="scope.row.edcVisitWindow != null && scope.row.edcVisitWindow.intervalType == 1">天</span>
          <span v-if="scope.row.edcVisitWindow != null && scope.row.edcVisitWindow.intervalType == 2">月</span>
        </template>
      </el-table-column>
      <el-table-column prop="edcVisitWindow.openNum" label="Open"> </el-table-column>
      <el-table-column prop="edcVisitWindow.closeNum" label="Close"> </el-table-column>
      <el-table-column prop="randomGiveMedicine" label="是否随机">
        <template slot-scope="scope">
          <span v-if="scope.row.randomGiveMedicine == 0"></span>
          <span v-if="scope.row.randomGiveMedicine == 1">是</span>
          <span v-if="scope.row.randomGiveMedicine == 2">否</span>
        </template>
      </el-table-column>
      <el-table-column prop="giveMedicine" label="是否发药">
        <template slot-scope="scope">
          <span v-if="scope.row.giveMedicine == 0"></span>
          <span v-if="scope.row.giveMedicine == 1">是</span>
          <span v-if="scope.row.giveMedicine == 2">否</span>
        </template>
      </el-table-column>
    </el-table>
    <!-- 排序 -->
    <el-dialog title="排序" width="500px" :visible.sync="openSort">
      <el-form label-width="160px" style="text-align: left" :size="size">
        <el-form-item label="目标顺序：">
          <el-select v-model="targetId" placeholder="请选择" filterable clearable>
            <el-option v-for="item in tableData" :key="item.id" :label="item.visitName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :size="size" @click.native="openSort = false">取消</el-button>
        <el-button :size="size" type="primary" @click.native="submitSort">提交</el-button>
      </div>
    </el-dialog>
    <addVisit :ruForm="dataForms" :editDialog="editDialog" :curTitle="curTitle" :exculdeRoles="exculdeRoles" :readonly="!isOperate" :edcDataBaseId="edcDataBaseId" :edcBuildProjectId="edcBuildProjectId" :dataBaseVersion="dataBaseVersion" :easyList=easyList :environment="environment" @addVisitCancal="addVisitCancal" @visitOk="visitOk"></addVisit>
  </div>
</template>

<script>
import addVisit from './component/add-visit.vue'
import { mapActions } from 'vuex'

export default {
  components: {
    addVisit
  },
  data() {
    return {
      number: 1,
      openSort: false,
      targetId: '',
      optionId: '',
      curTitle: '新增',
      dataForms: {
        textarea: '',
        excludeRoles: '',
        visitName: '',
        visitNum: '',
        visitType: '',
        roleIds: '',
        region: '',
        edcVisitWindow: {
          baselineVisit: '',
          baselineTable: '',
          baselineTime: '',
          intervalType: 0,
          intervalNum: 0,
          openNum: 0,
          closeNum: 0,
        },
        giveMedicine: 0,
        randomGiveMedicine: 0,
      },
      editDialog: false,
      orEdit: false,
      flag: false,
      size: 'mini',
      tableData: [],
      edcDataBaseId: '',
      multipleSelection: [],
      roleIds: [],
      easyList: [],
      readonly: false, // 页面是否只读的标识
      tableloading: false,
      editloading: false,
      exculdeRoles: [],
      edcBuildProjectId: '',
      dataBaseVersion: '',
      environment: '',
      isOperate: true
    }
  },
  mounted() {
    const databaseInfo = JSON.parse(localStorage.getItem('sys-database-info')) || {}
    if (databaseInfo.isLock === '1') {
      this.isOperate = false
    }

    this.edcBuildProjectId = localStorage.getItem('sys-project-id') || ''
    this.edcDataBaseId = databaseInfo.databaseId || ''
    this.dataBaseVersion = databaseInfo.databaseVersion || ''
    this.readonly = sessionStorage.getItem('edcDataBaseIsLock') === 1
    this.environment = sessionStorage.getItem('environment') || '0'
    this.findPage()
    // this.edcRole()
  },
  methods: {
    ...mapActions('visitDesign', ['visitList', 'visitDelete', 'visitBaselineTable', 'visitSortChange']),

    // 获取数据
    findPage () {
      this.tableloading = true
      const params = {
        databaseId: this.edcDataBaseId,
        databaseVersion: this.dataBaseVersion,
        projectId: this.edcBuildProjectId,
        environment: this.environment,
      }
      this.visitList({ params }).then(res => {
        if (res.code === 200) {
          this.tableData = res.data
          this.easyList = res.data
        }
        this.tableloading = false
      })
        .catch(error => {
          this.tableloading = false
          this.$message.error(error)
        })
    },

    // 刷新列表数据
    handleRefresh() {
      this.findPage()
    },

    visitOk () {
      this.editDialog = false
      this.findPage()
    },

    addVisitCancal () {
      this.editDialog = false
      this.findPage()
    },

    // 时间戳转换时间
    formatDate(row, column, cellValue, index) {
      if (cellValue == null || cellValue === '') return ''
    },

    // 排序
    handleSort(data) {
      this.openSort = true
      this.targetId = data.id
      this.optionId = data.id
    },

    // 排序提交
    submitSort() {
      if (this.targetId === '') {
        this.$message({
          type: 'error',
          message: '请选择目标顺序！',
        })
        return
      }
      if (this.optionId === this.targetId) {
        this.$message({
          type: 'error',
          message: '请选择与节点不同的目标节点！',
        })
        return
      }
      const data = {
        optionId: this.optionId,
        targetId: this.targetId,
      }
      this.visitSortChange({ data }).then(res => {
        if (res.code === 200) {
          this.findPage()
          this.openSort = false
          this.$message({
            type: 'success',
            message: '排序成功',
          })
        } else {
          this.$message({
            type: 'info',
            message: '获取失败。原因是：' + res.message,
          })
        }
      })
    },

    // 新增
    viewDetails() {
      this.editDialog = true
      this.curTitle = '新增'
      this.exculdeRoles = []
      this.dataForms.excludeRoles = ''
      this.dataForms.visitName = ''
      this.dataForms.visitNum = ''
      this.dataForms.visitType = ''
      this.dataForms.roleIds = ''
      this.dataForms.region = ''
      this.dataForms.edcVisitWindow.baselineVisit = ''
      this.dataForms.edcVisitWindow.baselineTable = ''
      this.dataForms.edcVisitWindow.baselineTime = ''
      this.dataForms.edcVisitWindow.intervalType = ''
      this.dataForms.edcVisitWindow.intervalNum = ''
      this.dataForms.edcVisitWindow.openNum = ''
      this.dataForms.edcVisitWindow.closeNum = ''
      this.dataForms.randomGiveMedicine = ''
      this.dataForms.giveMedicine = ''
      this.dataForms.textarea = ''
      this.dataForms.sort = this.tableData.length > 0 ? this.tableData[this.tableData.length - 1].sort || 0 : 0
      console.log('this.dataForms', this.dataForms)
    },
    // 查看
    lookDetails(row) {
      if (this.readonly) {
        this.curTitle = '查看'
      } else {
        this.curTitle = '编辑'
      }
      this.editDialog = true
      this.dataForms = row
      // this.dataForms.id = row.id
      // this.dataForms.visitName = row.visitName
      // this.dataForms.visitNum = row.visitNum
      // this.dataForms.visitType = row.visitType
      // this.dataForms.region = row.region
     
      // if (row.edcVisitWindow != null) {
      //   this.editloading = true
      //   this.dataForms.visitWindow.baselineVisit = ''
      //   this.dataForms.visitWindow.baselineTable = ''
      //   this.dataForms.visitWindow.baselineTime = ''
      //   // 清空之前基线数据,获取表单和日期列表待选项,之后再渲染新数据
      //   // this.getbaselineTable(true, row.visitWindow)
      //   this.dataForms.visitWindow.intervalType = row.visitWindow.intervalType
      //   this.dataForms.visitWindow.intervalNum = row.visitWindow.intervalNum
      //   this.dataForms.visitWindow.openNum = row.visitWindow.openNum
      //   this.dataForms.visitWindow.closeNum = row.visitWindow.closeNum
      // } else {
      //   this.dataForms.visitWindow.baselineVisit = ''
      //   this.dataForms.visitWindow.baselineTable = ''
      //   this.dataForms.visitWindow.baselineTime = ''
      //   this.dataForms.visitWindow.intervalType = ''
      //   this.dataForms.visitWindow.intervalNum = ''
      //   this.dataForms.visitWindow.openNum = ''
      //   this.dataForms.visitWindow.closeNum = ''
      // }
      // this.dataForms.randomGiveMedicine = row.randomGiveMedicine
      // this.dataForms.giveMedicine = row.giveMedicine
      // this.dataForms.textarea = row.loopName
      // 处理roleIds回显
      const roleIds = []
      const roleCodes = []
      this.exculdeRoles = row.excludeRoles
      if (row.excludeRoles != null) {
        for (const role of row.excludeRoles) {
          roleIds.push(role)
          roleCodes.push(role)
        }
      }
      this.dataForms.roleIds = roleIds.join(',')
      this.dataForms.excludeRoles = roleCodes.join(',')
      
    },
    /**
     *  获取基线表
     * @param {点击编辑时首次渲染} firstEdit
     * @param {访视窗数据} visitWindow
     */
    getbaselineTable(firstEdit, visitWindow) {
      let baselineVisit = null
      if (firstEdit) {
        baselineVisit = visitWindow.visitBaseline != null ? visitWindow.visitBaseline.id : null
      } else {
        baselineVisit = this.dataForms.visitWindow.baselineVisit
      }
      if (baselineVisit == null) {
        this.dataForms.visitWindow.baselineVisit = ''
        this.dataForms.visitWindow.baselineTable = ''
        this.editloading = false
        
      }
      // this.$api.homepage
      //   .baselineTable({
      //     visitId: baselineVisit,
      //     projectId: this.edcBuildProjectId,
      //     databaseNum: this.dataBaseVersion,
      //   })
      //   .then(res => {
      //     if (res.code === 200) {
      //       this.baselineList = res.data
      //       // 首次渲染表格取字段列表渲染基线日期列表
      //       if (firstEdit) {
      //         this.getbaselineTableDate(firstEdit, visitWindow)
      //       } else {
      //         this.dataForms.visitWindow.baselineTable = ''
      //         this.dataForms.visitWindow.baselineTime = ''
      //         this.baselineDateViewList = []
      //       }
      //       this.editloading = false
      //     } else {
      //       this.editloading = false
      //       this.$message({
      //         type: 'info',
      //         message: '获取失败。原因是：' + res.message,
      //       })
      //     }
      //   })
    },
    /**
     * 获取基线表时间字段
     * @param {点击编辑时首次渲染} firstEdit
     * @param {访视窗数据} visitWindow
     */
    getbaselineTableDate(firstEdit, visitWindow) {
      if (firstEdit) {
        this.dataForms.visitWindow.baselineVisit = visitWindow.visitBaseline != null ? visitWindow.visitBaseline.id : ''
        this.dataForms.visitWindow.baselineTable = visitWindow.tableBaseline != null ? visitWindow.tableBaseline.id : ''
        // 首次点击编辑,获取表单时间字段待选项列表，之后再渲染
        for (const form of this.baselineList) {
          if (this.dataForms.visitWindow.baselineTable === form.id) {
            this.baselineDateViewList = form.fieldList
          }
        }
        this.dataForms.visitWindow.baselineTime = visitWindow.baselineTime
      } else {
        // 手动选择表单后,取时间字段待选项列表,重置时间字段
        this.dataForms.visitWindow.baselineTime = ''
        for (const form of this.baselineList) {
          if (this.dataForms.visitWindow.baselineTable === form.id) {
            this.baselineDateViewList = form.fieldList
          }
        }
      }
    },


    // 删除
    handleDelete (row) {
      const params = {
        id: row.id
      }
      this.$confirm('确认删除吗？', '提示', { type: 'warning' }).then(() => {
        this.visitDelete({ params }).then(res => {
          if (res.code === 200) {
            this.$message({ message: '删除成功', type: 'success' })
            this.findPage()
          }
        })
      })
    },
  },
}
</script>

<style lang="scss" scoped>

</style>
